﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Globalization;

public partial class Leave : System.Web.UI.Page
{
    public static string loggedInUserName = "";
    public static string loggedInUserType = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["LoginName"] == null || Session["UserId"] == null)
        {
            Response.Redirect("Home.aspx");
        }
        else
        {
            if (!IsPostBack)
            {
                loggedInUserType = Session["UserType"].ToString();
                loggedInUserName = Session["LoginName"].ToString();
                FillDropdowns();
            }
        }
    }

    private void FillDropdowns()
    {
        ArrayList groups = new ArrayList();
        ArrayList allGroups = new ArrayList();

        if (Session["UserTypeId"] != null)
            groups = EventDAO.getGroups(Convert.ToInt32(Session["UserTypeId"]), Convert.ToInt32(Session["level"]));

        allGroups.Add("Select one group");
        allGroups.AddRange(groups);

        addGroups.DataSource = allGroups;
        addGroups.Items.Insert(0, new ListItem("Select one group"));
        addGroups.DataBind();
    }

    protected void btnApplyLeave_Click(object sender, EventArgs e)
    {
        if (txtFrom.Text == null || txtTo.Text == null || txtFrom.Text.Trim().Equals(String.Empty) || txtTo.Text.Trim().Equals(String.Empty))
        {
            ErrorMessage.Text = "Date fields cannot be empty.";
        }
        else
        {
            try
            {
                //var enCulture = new System.Globalization.CultureInfo("en-us");
                //DateTime result = DateTime.ParseExact("30/05/2015","dd/MM/yyyy",enCulture);

                string[] toParseStartDate = txtFrom.Text.Split('/');
                double startMonth = Convert.ToDouble(toParseStartDate[0]);
                double startDate = Convert.ToDouble(toParseStartDate[1]);
                double startYear = Convert.ToDouble(toParseStartDate[2]);

                string[] toParseEndDate = txtTo.Text.Split('/');
                double endMonth = Convert.ToDouble(toParseEndDate[0]);
                double endDate = Convert.ToDouble(toParseEndDate[1]);
                double endYear = Convert.ToDouble(toParseEndDate[2]);

                //DateTime dtStart = DateTime.ParseExact(txtFrom.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
                //DateTime dtEnd = DateTime.ParseExact(txtTo.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);

                //string startTime = Convert.ToString(leaveStartTime.Value);
                //string endTime = Convert.ToString(leaveEndTime.Value);

                //string[] startParams = startTime.Split(':');
                //string[] endParams = endTime.Split(':');

                //double startHours = Convert.ToDouble(startParams[0]);
                //double startMins = Convert.ToDouble(startParams[1]);
                //double endHours = Convert.ToDouble(endParams[0]);
                //double endMins = Convert.ToDouble(endParams[1]);

                double startHours = Convert.ToDouble(startTimeHour.Value);
                double startMins = Convert.ToDouble(startTimeMin.Value);
                double endHours = Convert.ToDouble(endTimeHour.Value);
                double endMins = Convert.ToDouble(endTimeMin.Value);

                DateTime dtStart = new DateTime(Convert.ToInt32(startYear), Convert.ToInt32(startMonth), Convert.ToInt32(startDate));
                DateTime dtEnd = new DateTime(Convert.ToInt32(endYear), Convert.ToInt32(endMonth), Convert.ToInt32(endDate));

                dtStart = dtStart.AddHours(startHours);
                dtStart = dtStart.AddMinutes(startMins);
                dtEnd = dtEnd.AddHours(endHours);
                dtEnd = dtEnd.AddMinutes(endMins);

                // If from date is less than To date
                if (dtStart > dtEnd)
                {
                    ErrorMessage.Text = "From date cannot be greater than To date.";
                }
                else
                {
                    if (addUsers.Items.Count > 0)
                    {
                        for (int i = 0; i < addUsers.Items.Count; i++)
                        {
                            if (addUsers.Items[i].Selected)
                            {
                                string selectedItem = addUsers.Items[i].Text;
                                User user = EventDAO.getUserByName(selectedItem);

                                int leaveId = EventDAO.addLeave(Convert.ToInt32(user.userId), LeaveTitle.Text, LeaveDesc.Text, dtStart.ToString(), dtEnd.ToString());
                                //int leaveId = EventDAO.addLeave(Convert.ToInt32(user.userId), LeaveTitle.Text, LeaveDesc.Text, txtFrom.Text, txtTo.Text);
                            }
                        }

                        lblStatus.Text = "You have succesfully applied leave.";
                        //lnkBtnLogin.Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessage.Text = "There is some problem in applying leave now. Please try again later." + ex.Message.ToString();
            }
        }
    }

    protected void addGroups_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selGroupName = this.addGroups.SelectedItem.Text;
        ArrayList users = EventDAO.getUsersForAGroup(selGroupName);
        ArrayList usersToBind = new ArrayList();

        string[] strings = Array.ConvertAll<object, string>(users.ToArray(), Convert.ToString);
        if (loggedInUserType != null && loggedInUserType.Equals(selGroupName))
        {
            usersToBind.Add(loggedInUserName);
        }
        else
        {
            for (int i = 0; i < strings.Length; i++)
            {
                usersToBind.Add(strings[i].ToString());
            }
        }

        addUsers.DataSource = usersToBind;
        addUsers.DataBind();
    }
}
